package com.ouroboroswiki.core.content.velocity;

import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.app.VelocityEngine;

import com.ouroboroswiki.core.AbstractContentRepository;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentPath;
import com.ouroboroswiki.core.ContentRepository;
import com.ouroboroswiki.core.ContentUtil;
import com.ouroboroswiki.core.Version;
import com.ouroboroswiki.core.VersionBuilder;

public class VelocityTemplatingContentRepository extends AbstractContentRepository {

	private ContentRepository source;
	private Map<String, Object> globalProperties;
	private VelocityEngine engine;
	
	public VelocityTemplatingContentRepository( VelocityEngine engine, String name, Map<String, Object> globalProperties ) {
		this.engine = engine;
		this.setName( name );
		this.globalProperties = globalProperties;
	}
	
	public ContentRepository getSource() {
		return source;
	}

	public void setSource(ContentRepository source) {
		this.source = source;
	}

	@Override
	public Version buildVersion(Object principal, ContentPath path,
			String[] versionPath, VersionBuilder versionBuilder)
			throws ContentException {
		// TODO : get the child version, not this version
		return source.buildVersion(principal, path, versionPath, versionBuilder);
	}

	@Override
	public boolean exists(Object principal, ContentPath path)
			throws ContentException {
		return source.exists(principal, path);
	}

	@Override
	public Content getContent(Object principal, ContentPath path,
			Version version, Map<String, Object> properties)
			throws ContentException {
		Content sourceContent = source.getContent(principal, path, ContentUtil.getChildVersion(version, Content.CHILD_CONTENT_MAIN), properties);
		HashMap<String, Object> contentProperties = new HashMap<String, Object>( properties );
		contentProperties.putAll(this.globalProperties);
		VelocityTemplatingContent result = new VelocityTemplatingContent(engine, sourceContent, contentProperties);
		ContentUtil.assignAllAttributes(sourceContent, result, this.getName(), version, false);
		return result;
	}
}
